package com.xingchen.feima.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xingchen.feima.common.base.exception.FeimaException;
import com.xingchen.feima.common.utils.R;
import com.xingchen.feima.common.utils.ResultCode;
import com.xingchen.feima.system.entity.Menu;
import com.xingchen.feima.system.utils.MenuHelper;
import com.xingchen.feima.system.service.MenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "菜单管理")
@RestController
@RequestMapping("/system/menu")
public class MenuController {

    @Autowired
    private MenuService menuService;


    @ApiOperation(value = "所有菜单列表")
    @GetMapping("")
    public R list(){
        // 获取全部菜单数据
        List<Menu> list = menuService.list(null);
        if (CollectionUtils.isEmpty(list)) return null;
        // 构建数据数据
        List<Menu> TreeResult = MenuHelper.buildTree(list);
        return R.ok().data("items", TreeResult);
    }

    @ApiOperation(value = "新增菜单")
    @PostMapping("")
    public R add(
            @ApiParam(name = "menu", value = "菜单对象", required = true)
            @RequestBody Menu menu){

        menuService.save(menu);
        return R.ok();
    }

    @ApiOperation(value = "根据ID修改菜单")
    @PutMapping("")
    public R updateById(
            @ApiParam(name = "menu", value = "菜单对象", required = true)
            @RequestBody Menu menu){

        menuService.updateById(menu);
        return R.ok();
    }

    @ApiOperation(value = "根据ID删除菜单")
    @DeleteMapping("{id}")
    public R removeById(
            @ApiParam(name = "id", value = "菜单ID", required = true) @PathVariable Long id){
        long count = menuService.count(new QueryWrapper<Menu>().eq("parent_id", id));
        if (count > 0) {
            throw new FeimaException(ResultCode.ERROR, "请先删除子节点");
        }
        menuService.removeById(id);
        return R.ok();
    }

}

